package com.woniu.his.dms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.his.dms.common.DmsResultCode;
import com.woniu.his.dms.infra.model.CaseModel;
import com.woniu.his.dms.infra.mapper.CaseModelMapper;
import com.woniu.his.dms.service.CaseDiseModelRelationService;
import com.woniu.his.dms.service.CaseModelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.his.dms.service.dto.CaseModelDto;
import com.woniu.his.dms.service.param.AddOrUpdateCaseModelParam;
import com.woniu.his.exception.HisException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 病历模板 服务实现类
 * </p>
 *
 * @author ZJH
 * @since 2022-11-27
 */
@Service
public class CaseModelServiceImpl extends ServiceImpl<CaseModelMapper, CaseModel> implements CaseModelService {

    @Resource
    private CaseDiseModelRelationService caseDiseModelRelationService;

    @Override
    public Boolean addOrUpdateCaseModel(AddOrUpdateCaseModelParam param) {
        CaseModel caseModel = BeanUtil.copyProperties(param, CaseModel.class);
        if(param.getId()==null){
            //新增模板
            save(caseModel);
            caseDiseModelRelationService.createCaseDiseRelation(caseModel.getId(),param.getDiseId());
        }else{
            //更新模板
            CaseModel model = getById(param.getId());
            if(caseModel==null) throw new HisException(DmsResultCode.CASE_MODEL_NOT_EXISTS);
            updateById(caseModel);
        }
        return true;
    }

    @Override
    public CaseModelDto queryCaseModelById(Long id) {
        CaseModel caseModel = getById(id);
        if(caseModel==null) throw new HisException(DmsResultCode.CASE_MODEL_NOT_EXISTS);
        CaseModelDto caseModelDto = BeanUtil.copyProperties(caseModel, CaseModelDto.class);
        return caseModelDto;
    }

    @Override
    public Boolean deleteCaseModelByIds(List<Long> ids) {
        List<CaseModel> caseModels = list(new QueryWrapper<CaseModel>().in("id", ids));
        if(caseModels.size()!=ids.size()) throw new HisException(DmsResultCode.PART_CASE_MODEL_ALREADY_DELETED);
        removeByIds(ids);
        return true;
    }
}
